package edu.suda.LoopCodePlus.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.suda.LoopCodePlus.common.Result;
import edu.suda.LoopCodePlus.entity.Collections;
import edu.suda.LoopCodePlus.entity.Problem;
import edu.suda.LoopCodePlus.service.CollectionService;
import edu.suda.LoopCodePlus.service.ProblemService;
import edu.suda.LoopCodePlus.service.SubmissionService;
import edu.suda.LoopCodePlus.service.UserService;
import edu.suda.LoopCodePlus.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/problem")
@Slf4j
public class ProblemController {
    @Autowired
    private ProblemService problemService;
    @Autowired
    private SubmissionService submissionService;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private CollectionService collectionService;
    @GetMapping("/list")
    public Result list(@RequestParam("page") Integer page,
                       @RequestParam(value = "tag" ,required = false) ArrayList<String> tag,
                       @RequestParam(value = "collection", required = false) ArrayList<String> collection,
                       @RequestParam("userId") Integer userId) throws JsonProcessingException {
        System.out.println("请求进来了");
        System.out.println("请求id:"+userId);
        System.out.println("请求页数:"+page);
        System.out.println("筛选标签:"+tag);
        System.out.println("筛选题目集:"+collection);
        String a1=null;
        String a2=null;
        if(tag!=null) {
            ObjectMapper mapper1 = new ObjectMapper();
            a1 = mapper1.writeValueAsString(tag);
        }
        if(collection!=null) {
            ObjectMapper mapper2 = new ObjectMapper();
            a2 = mapper2.writeValueAsString(collection);
        }
        //找出所有题目
        List<Problem> ProblemList;
        try {
            ProblemList = problemService.findPublicAll(a1, a2, 1);
        }catch (Exception e){
            return Result.failure();
        }

        //根据标签筛查
        //将arraylist转为json字符串
        System.out.println(ProblemList);
        System.out.println(ProblemList.subList((page-1)*30, Math.min(ProblemList.size(), page * 30)));
        HashMap<String, Object> result = new HashMap<>();
        result.put("problemList", ProblemList.subList((page-1)*30, Math.min(ProblemList.size(), page * 30)));
        System.out.println("当前页面显示的题目:"+ProblemList);
        //找出用户其中通过的题目
        Set<Integer> problemNum;
        List<Integer> pids = new ArrayList<>();
        for(Problem problem:ProblemList){
            pids.add(problem.getProblemId());
        }
        try {
            problemNum = submissionService.findAllByUserId(userId, pids);
        }catch (Exception e){
            return Result.failure();
        }
        result.put("problemNum", problemNum);
        System.out.println("用户通过的题目列表:"+problemNum);
        return Result.success(result, ProblemList.size());
    }

    @PostMapping("/add")
    public Result add(@RequestBody Problem problem,
                      HttpServletRequest request,
                      HttpServletResponse response) {
        System.out.println("收到添加或修改题目的请求");
        System.out.println("验证token");
        String token = request.getHeader("Authorization");
        Integer userId;
        try {
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token);
            userId = Integer.parseInt(decodedJWT.getClaim("userId").asString());
            System.out.println("token验证成功，userId:"+userId);
        }catch (Exception e){
            System.out.println("token验证失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return Result.failure("token验证失败");
        }
        System.out.println("参数验证");
        try {
            if (problem == null) {
                System.out.println("该问题为null,不符合要求");
                return Result.failure();
            }
            if (userService.findUserById(problem.getUserId()) == null || userService.findUserById(userId) == null) {
                System.out.println("用户不存在");
                return Result.failure();
            }
        }catch (Exception e){
            System.out.println("参数错误");
            return Result.failure();
        }
        System.out.println("参数验证通过");
        Integer problemId=problem.getProblemId();
        if(problemId!=null){
            System.out.println("修改已有的题目");
            try{
                if(problemService.updateProblemById(problemId, userId, problem)){
                    return Result.success();
                }
                else{
                    System.out.println("题目修改失败");
                    return Result.failure();
                }
            }catch (Exception e){
                System.out.println("题目修改失败");
                return Result.failure();
            }
        }
        System.out.println("添加新的题目");
        //还需要做具体的参数验证
        System.out.println("参数验证通过");
        System.out.println(problem);
        if(problemService.addProblem(problem)){
            System.out.println("题目添加成功:"+problem);
            return Result.success();
        }
        System.out.println("题目添加失败,数据库插入错误");
        return Result.failure();
    }
    /*****
     * 获取题目信息
     */
    @GetMapping("/getContent")
    public Result getContent(@RequestParam("problemId") Integer problemId) {
        System.out.println("收到获取题目信息的请求");
        System.out.println("参数验证");
        if(problemId==null){
            System.out.println("参数错误");
            return Result.failure();
        }
        System.out.println("参数验证通过");
        System.out.println("problemId:"+problemId);
        Problem problem;
        try {
            problem = problemService.findProblemById(problemId);
            if(problem==null){
                System.out.println("题目不存在");
                return Result.failure();
            }
        }catch (Exception e){
            return Result.failure();
        }
        return Result.success(problem);
    }


    @GetMapping("/myList")
    public Result myList(@RequestParam("page") Integer page,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        System.out.println("收到获取个人题目信息的请求");
        System.out.println("验证token");
        String token = request.getHeader("Authorization");
        Integer userId;
        try {
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token);
            userId = Integer.parseInt(decodedJWT.getClaim("userId").asString());
            System.out.println("token验证成功，userId:"+userId);
        }catch (Exception e){
            System.out.println("token验证失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return Result.failure("token验证失败");
        }
        List<Problem> ProblemList;
        try{
            ProblemList = problemService.findAllByUserId(userId);
            System.out.println("个人题目列表:"+ProblemList);
            return Result.success(ProblemList.subList((page-1)*30, Math.min(ProblemList.size(), page * 30)), ProblemList.size());
        }catch (Exception e){
            System.out.println("数据库查询失败");
            return Result.failure();
        }
    }

    @DeleteMapping("/delete")
    public Result delete(@RequestParam("problemId") Integer problemId,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        System.out.println("收到删除个人题目信息的请求");
        System.out.println("验证token");
        String token = request.getHeader("Authorization");
        Integer userId;
        try {
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token);
            userId = Integer.parseInt(decodedJWT.getClaim("userId").asString());
            System.out.println("token验证成功，userId:"+userId);
        }catch (Exception e){
            System.out.println("token验证失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return Result.failure("token验证失败");
        }

        try{
            if(problemService.deleteProblemById(problemId, userId)){
                System.out.println("题目删除成功,题目已经修改至管理员账户下,userId=39");
                return Result.success();
            }
            System.out.println("题目删除失败");
            return Result.failure();

        }catch (Exception e){
            System.out.println("题目删除失败");
            return Result.failure();
        }
    }

    @GetMapping("/updateContent")
    public Result getContent(@RequestParam("problemId") Integer problemId,
                             HttpServletRequest request,
                             HttpServletResponse response) {
        System.out.println("收到获取题目信息的请求");
        System.out.println("参数验证");
        System.out.println("验证token");
        String token = request.getHeader("Authorization");
        Integer userId;
        try {
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token);
            userId = Integer.parseInt(decodedJWT.getClaim("userId").asString());
            System.out.println("token验证成功，userId:"+userId);
        }catch (Exception e){
            System.out.println("token验证失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return Result.failure("token验证失败");
        }
        if(problemId==null){
            System.out.println("参数错误");
            return Result.failure();
        }
        System.out.println("参数验证通过");
        System.out.println("problemId:"+problemId);
        Problem problem;
        try {
            problem = problemService.findProblemById(problemId);
            if(problem==null){
                System.out.println("题目不存在");
                return Result.failure();
            }
        }catch (Exception e){
            return Result.failure();
        }
        return Result.success(problem);
    }

    @GetMapping("/colList")
    public Result colList() {
        try{
            List<Collections> collectionList = collectionService.findCollectionByStatus(1);
            if(collectionList==null){
                System.out.println("数据库查询失败");
                return Result.failure("数据库查询失败");
            }
            System.out.println("数据库查询成功:"+collectionList);
            return Result.success(collectionService.findCollectionByStatus(1));
        }catch (Exception e){
            System.out.println("数据库查询失败");
            return Result.failure("数据库查询失败");
        }
    }
}
